package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 小视频服务接口实现类
 */
@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Video video) {
        video.setId(ObjectId.get());//主键id
        video.setCreated(System.currentTimeMillis());//当前系统发布小视频时间
        mongoTemplate.save(video);
    }

    /**
     * 小视频列表查询
     */
    @Override
    public PageResult<Video> querySmallVideos(int page, int pagesize) {
        page=page<1?1:page;
        //1.总记录数
        PageRequest pageRequest = PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query();
        query.with(pageRequest);
        long counts = mongoTemplate.count(query, Video.class);
        //2.根据条件分页查询小视频列表
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        //3.封装返回PageResult
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<Video>(counts,(long)pagesize,pages,(long)page,videoList);
    }
    /**
     * 关注用户
     */
    @Override
    public void followUser(FollowUser followUser) {
        followUser.setId(ObjectId.get());
        followUser.setCreated(System.currentTimeMillis());
        mongoTemplate.save(followUser);
    }
    /**
     * 取消关注用户
     */
    @Override
    public void unfollowUser(FollowUser followUser) {
        Query query = new Query(
                Criteria.where("userId")
                        .is(followUser.getUserId())
                        .and("followUserId").is(followUser.getFollowUserId()));
        mongoTemplate.remove(query,FollowUser.class);
    }
}
